﻿/// <reference path="jquery-1.4.2.min-vsdoc.js"/>
/// <reference path="../config/sw-config-default.js"/>
/// <reference path="../const/sw-const.js"/>
/// <reference path="sw-prototype.js"/>
/// <reference path="sw-controls.js"/>

$sw = function (uicode, container, modulename) {
    /// <summary>Smart UI JS开发支持库</summary>
};
///#region 全局变量
$sw.globalParams = {
    urlParams: null//url参数
    , currentDate: new Date()//当前时间
    , currentUI: null//当前ui
    , contentID: null//当前加载内容区域
    , client: null
    , globalFn:null
}
$sw.loadGlobalParams = function () {
    //    $sw.globalParams.currentUI = $.cookie("sw_gp_ui");
    var client = $.cookie("sw_gp_client");
    if (client)
        $sw.globalParams.client = $sw.parseJSON(client);

    var nowDate = $.cookie("sw_gp_now");
    if (nowDate) {
        nowDate = jsonToDate($sw.parseJSON('{"Date":"' + nowDate + '"}').Date);
        if (nowDate)
            $sw.globalParams.currentDate = nowDate;
    }
}
//$sw.saveUI = function (ui) {
//    $.cookie("sw_gp_ui", ui);
//}
//$sw.saveClient = function (client) {

//    $.cookie("sw_gp_client", client);
//}
$sw.setGlobalData = function (data) {
    /// <summary>设置全局参数</summary>
    //设置用户信息
    $sw.globalParams.client = data.Client ? $sw.parseJSON(data.Client) : null;
    $.cookie("sw_gp_client", data.Client);
    //设置服务器端时间

    var nowDate = jsonToDate($sw.parseJSON('{"Date":"' + data.CurrentDate + '"}').Date);
    if (nowDate)
        $sw.globalParams.currentDate = nowDate;
    $.cookie("sw_gp_now", data.CurrentDate);
}
$sw.addGlobalFn = function (fn) {
    /// <summary>注册全局方法</summary>
    /// <param name="fn" type="Function">注册的方法</param>
    if ($sw.globalParams.globalFn == null)
        $sw.globalParams.globalFn = new Array();
    $sw.globalParams.globalFn.push(fn);
}
///#endregion
///#region 核心操作
$sw.PostData = function () {
    this.No = '';
//    this.ClientID = '';
    this.Body = '';
};
$sw.ajax = function (data, url, fnsucess, fnerror) {
    /// <summary>post执行的操作</summary>
    /// <param name="data" type="String">postData的对象</param>
    /// <param name="url" type="String">目标url</param>
    /// <param name="fnsucess" type="function">【非必要属性】,请求成功后的操作
    /// <param name="fnerror" type="function">【非必要属性】,请求失败后的操作</param>
    $.ajax({
        data: $sw.toJsonStr(data),
        url: url,
        type: "POST",
        cache: false,
        success: fnsucess,
        error: function () { $icontrol.alert($iconst.Common.error); if (fnerror) fnerror(); }
    });
}
$sw.DO = function (fncode, data, fnsucess, fnerror) {
    /// <summary>post执行的操作</summary>
    /// <param name="fncode" type="String">functionCode</param>
    /// <param name="data" type="String">【非必要属性】,传入的对象参数</param>
    /// <param name="fnsucess" type="function">【非必要属性】,请求成功后的操作,fnsucess（r）r:返回的值</param>
    /// <param name="fnerror" type="function">【非必要属性】,请求失败后的操作</param>
    var d = new $sw.PostData();
    d.No = fncode;
    if (data)
        d.Body = typeof (data) == "string" ? data : $sw.toJsonStr(data);
    $sw.ajax(d, iconfig.handles.post,
    function (data) {
        $sw.setGlobalData(data);

        if (data.ErrorType)//统一处理错误
        {
            $sw.Error(data.ErrorType, data.Error);
            if(fnerror)
                fnerror($sw.parseBody(data));
        }
        else
            fnsucess($sw.parseBody(data));
    }, fnerror);
}
$sw.UI = function (uicode, container, params, fnerror) {
    /// <summary>UI加载的操作</summary>
    /// <param name="uicode" type="String">UI Code</param>
    /// <param name="container" type="DomStrorJQSelect">填充的对象</param>
    /// <param name="params" type="Json">【非必要属性】,url参数</param>
    /// <param name="fnerror" type="function">【非必要属性】,请求失败后的操作</param>
    if (uicode !== '#') {
        var page = getJsonValue($page, uicode);
        if (page && page.url) {
            var url = window.location.href, lastIndex = url.lastIndexOf('/'), curMaster = '';
            if (lastIndex != url.length - 1) {
                var endIndex = url.indexOf('?');
                curMaster = url.substring(lastIndex + 1, (endIndex > 0 ? endIndex : url.length)).toLocaleLowerCase();
            }
            var master = $master[page.master ? page.master : 0].toLocaleLowerCase();
            if (master === curMaster || (master == '' && curMaster === $commonpage.defmaster)
            || (curMaster == '' && master === $commonpage.defmaster)) {
                if (params)
                    $sw.SetUIParam(params);
                var path = page.path || 0;
                $sw.LoadPage($pagepath[path] + page.url, container);
                //设置当前ui
                $sw.globalParams.currentUI = uicode;

                if ($sw.globalParams.globalFn) {
                    $.each($sw.globalParams.globalFn, function (i, fn) { fn(); });
                }
                //                $sw.saveUI(uicode);
            }
            else {
                url = (master || '/') + '?u=' + uicode;
                if (params) {
                    url += '&' + params;
                }
                window.location.href = url;
            }
        }
        else {
            $sw.LoadPage($commonpage.nopage, container);
        }
    }
}
//$sw.DL = function (fncode, data, fnsuccess, fnerror) {
//    /// <summary>post执行的操作</summary>
//    /// <param name="fncode" type="String">functionCode</param>
//    /// <param name="data" type="String">传入的对象参数</param>
//    /// <param name="fnsucess" type="function">【非必要属性】,请求成功后的操作,fnsucess（r）r:返回的值</param>
//    /// <param name="fnerror" type="function">【非必要属性】,请求失败后的操作</param>
//    var d = new $sw.PostData();
//    d.No = fncode;
//    d.Body = $sw.toJsonStr(data);
//    $sw.ajax(d, "/Handlers/download.ashx", fnsuccess, fnerror);
//}
$sw.Error = function (errortype, msgno) {
    /// <summary>系统公共错误处理</summary>
    if (msgno)//自定消息
        $icontrol.alert(getJsonValue($iconst.msg, msgno));
    else {
        switch (errortype) {
            case 2: //未登录
                $icontrol.alertAndGoto($iconst.Common.login, 'site');
                break;
            case 3: //没有权限
                $icontrol.alertAndGoto($iconst.Common.noright, 'site');
                break;
            case 4: //请求错误
                $icontrol.alert($iconst.Common.error);
                break;
            case 5: //fncode错误
                $icontrol.alert($iconst.Common.fncodeerror);
                break;
        }
    }
}

$sw.init = function (ui, container, params) {
    /// <summary>主(master)页面初始化方法</summary>
    /// <param name="ui" type="String">UICode</param>
    /// <param name="container" type="JQSelector||Dom">加载区域选择器</param>
    /// <param name="params" type="String">参数</param>
    $sw.loadGlobalParams();//加载缓存的全局变量

    $sw.globalParams.urlParams = getUrlParam();

    if ($sw.globalParams.urlParams && $sw.globalParams.urlParams.u) {
        //        $sw.globalParams.urlParams.u = decode($sw.globalParams.urlParams.u);
        if ($sw.globalParams.urlParams.u)//判断是否有最近一次uicode的记录
            ui = $sw.globalParams.urlParams.u;
    }
//    else if ($sw.globalParams.currentUI)
//        ui = $sw.globalParams.currentUI;

    if (ui)
        $sw.UI(ui, container, params);

    $sw.globalParams.contentID = container;
   
};
///#endregion

///#region 页面跳转
$sw.GotoPage = function (uicode, params) {
    /// <summary>页面跳转</summary>
    /// <param name="uicode" type="String">UI Code</param>
    /// <param name="params" type="Json">【非必要属性】,url参数</param>
    var url = $sw.getCurrentUrl(uicode, params);
    if (url)
        window.location.href = url;
}
$sw.OpenPage = function (uicode, params) {
    /// <summary>打开新页面</summary>
    /// <param name="uicode" type="String">UI Code</param>
    /// <param name="params" type="Json">【非必要属性】,url参数</param>
    var url = $sw.getCurrentUrl(uicode, params);
    if (url)
        window.open(url);
}
$sw.LoadUI = function (uicode, container) {
    /// <summary>根据UICode在指定区域类加载内容页面</summary>
    /// <param name="uicode" type="String">UI Code</param>
    /// <param name="container" type="JQSelector||Dom">加载区域选择器</param>
    var page = getJsonValue($page, uicode), url;
    if (page && page.url) {
        var path = page.path || 0;
        url = $pagepath[path] + page.url;
    }
    else
        url = $commonpage.nopage;
    $sw.LoadPage(url, container);
}
$sw.getCurrentUrl = function (uicode, params) {
    /// <summary>根据UICode获取正确的Url</summary>
    /// <param name="uicode" type="String">UI Code</param>
    /// <param name="params" type="Json">【非必要属性】,url参数</param>
    if (uicode !== '#') {
        if (!uicode || uicode == '/') {
            uicode = '/';
            if (params)
                uicode = '/?' + params;
            return uicode;
        }
        var page = getJsonValue($page, uicode), url;
        if (page && page.url) {
            master = $master[page.master ? page.master : 0];

            url = (master || '/') + '?u=' + uicode;
            if (params)
                url += '&' + params;
            return url;
        }
        else {
            return url = '/?=nopage';
        }
    }
}
$sw.getUrl = function (uicode) {
    /// <summary>根据uicode获取url</summary>
    /// <param name="uicode" type="String">UI Code</param>
    if (uicode !== '#') {
        var url = window.location.href;
        var lastIndex = url.lastIndexOf('/'), curMaster = '', master = '';
        if (lastIndex != url.length) {
            curMaster = url.substring(lastIndex, url.indexOf('.'));
        }
        page = getJsonValue($page, uicode);
        if (hasValue(page.master))
            master = $master[page.master];
        if (master === curMaster)
            return page.url;

        return page.url();
    }
    return null;
}
$sw.LoadPage = function (url, container) {
    /// <summary>页面跳转</summary>
    /// <param name="url" type="String">加载内容的路径</param>
    /// <param name="params" type="Json">【非必要属性】,url参数</param>
    if (!container)
        container = $sw.globalParams.contentID || iconfig.system.defcontainer;
    $(container).load(url);
}
///#endregion

///#region 数据转换
$sw.toJsonStr = function (data) {
    /// <summary>Json转换成字串</summary>
    /// <param name="data" type="Json">Json对象</param>
    /// <returns type="String" />
    return iJSON.stringify(data);
};

$sw.parseJSON = function (data) {
    /// <summary>String转换成Json</summary>
    /// <param name="data" type="String">要转换的字串</param>
    /// <returns type="Json" />
    return iJSON.parse(data);
};
$sw.parseBody = function (data) {
    /// <summary>只针对data.Body转换,Smart UI特有格式</summary>
    /// <param name="data" type="String">要转换的字串</param>
    /// <returns type="Json" />
    if (data && data.Body)
        return $sw.parseJSON("[" + data.Body + "]")[0];
    return null;
};
///#endregion

///#region 公共方法
$sw.getUIParam = function () {
    /// <summary>获取UI参数</summary>
    return $($sw.globalParams.contentID || iconfig.system.defcontainer).data('sw_uiparam');
}
$sw.SetUIParam = function (params) {
    /// <summary>设置UI参数</summary>
    /// <param name="params" type="Object">参数值</param>
    /// <returns type="Object" />
    return $($sw.globalParams.contentID || iconfig.system.defcontainer).data('sw_uiparam', params);
}
$sw.bulidSearchParam = function (pageindex, pagesize, where, sort) {
    /// <summary>生成查询参数</summary>
    /// <param name="pageindex" type="Number">显示页面的页数</param>
    /// <param name="pagesize" type="Number">每页显示的记录条数</param>
    /// <param name="where" type="String">查询条件参数</param>
    /// <param name="sort" type="String">排序语句</param>
    /// <returns type="Object" />
    return $sw.toJsonStr({
        PageIndex: pageindex,
        PageSize: pagesize,
        Sort: sort,
        Where: where ? where : null
    })
}
$sw.getEnum = function (enumname) {
    /// <summary>动态获得定义的枚举对象</summary>
    /// <param name="enumname" type="String">Js枚举名称</param>
    /// <returns type="Object" />
    try {
        return new Function('return $iconst.Enum.' + enumname).call();
    }
    catch (err) { return null; }
}
var enums = function () { };//临时缓存枚举对象
$sw.getEnumText = function (enumname, value) {
    /// <summary>根据value，获得定义的枚举文本,为空时返回''</summary>
    /// <param name="enumname" type="String">Js枚举名称</param>
    /// <param name="value" type="Number">枚举值</param>
    /// <returns type="String" />
    var text = new Function('var en = enums.' + enumname + ';if(!en){en = new function(){};var datas = $iconst.Enum.' + enumname + ';for(var i =0;datas[i];i++)en = bindEnumData(en, datas[i].Key, datas[i].Value); }enums.' + enumname + '=en; return en.k' + value + ';').call();
    if (hasValue(text) && (text+'') != 'NaN')
        return text;
    return '';
}
function bindEnumData(en, key, value) {
    /// <summary>动态绑定枚举数据</summary>
    /// <param name="en" type="Array">枚举数组</param>
    /// <param name="key" type="String">枚举key</param>
    /// <param name="value" type="String">枚举Value</param>
    /// <returns type="Object" />
    return new Function('en','en.k' + key + ' = "' + value + '";return en;').call(this,en);
}
///#endregion